﻿using System;
using DocLibraryReplicator.AppCode;
using Microsoft.SharePoint;

namespace DocLibraryReplicator.Document_Library_Receiver
{
    /// <summary>
    /// List Item Events
    /// </summary>
    public class Document_Library_Receiver : SPItemEventReceiver
    {
        /// <summary>
        /// An item was added.
        /// </summary>
        public override void ItemAdded(SPItemEventProperties properties)
        {
            base.ItemAdded(properties);
        }

        /// <summary>
        /// An item was updated.
        /// </summary>
        public override void ItemUpdated(SPItemEventProperties properties)
        {
            base.ItemUpdated(properties);
            replicatorOperation(properties, "Added/Updated");
        }

        /// <summary>
        /// An item is being added
        /// </summary>
        public override void ItemAdding(SPItemEventProperties properties)
        {
            base.ItemAdding(properties);
        }

        /// <summary>
        /// An item was deleted
        /// </summary>
        public override void ItemDeleted(SPItemEventProperties properties)
        {
            base.ItemDeleted(properties);
            replicatorOperation(properties, "Deleted");
        }

        public void replicatorOperation(SPItemEventProperties properties, string operation)
        {
            using (SPSite spsite = new SPSite(properties.WebUrl))
                try
                {
                    EventFiringEnabled = false;
                    if (properties.ListItem.ParentList.Title != "Replicator Logger")
                    {
                        SPWeb siteForLogger = spsite.OpenWeb();
                        // determine target filename - the same as the source
                        string targetfilename = properties.ListItem.Name.ToString();
                        string SourceLibPath = properties.WebUrl + "/" + properties.ListItem.ParentList.ToString();
                        string sourceLibrary = properties.ListItem.ParentList.ToString();

                        string targetLibraryFromConfigList = SPListOperations.queryConfigList(siteForLogger, sourceLibrary).ToString();

                        // Query the Configuration List

                        if (targetLibraryFromConfigList != "NotListed")
                        {
                            // Copy/Delete the file to the destination library (targetlibrary)
                            if (operation == "Added/Updated")
                            {
                                properties.ListItem.File.CopyTo(targetLibraryFromConfigList + "/" + targetfilename, true);
                            }
                            if (operation == "Deleted")
                            {
                                SPFile spFileTarget = siteForLogger.GetFile(targetLibraryFromConfigList + "/" + targetfilename);
                                spFileTarget.Delete();
                            }

                            // Write to the Replicator Log - unfinished...
                            ReplicatorLogger replogger = new ReplicatorLogger();

                            // Get the current Date and Time
                            DateTime dtime = DateTime.Now;

                            // Create the title for the logger list item
                            string title = (dtime.Date.ToString() + "_" + dtime.Hour.ToString() + "_" + dtime.Minute.ToString() + "_" + dtime.Second.ToString() + "_" + targetfilename.ToString());

                            // Write the information to the logger list

                            // Write to the log list
                            EventFiringEnabled = false;
                            replogger.writeToLog(title, dtime.ToShortDateString(), properties.UserDisplayName.ToString(), operation, SourceLibPath, targetfilename, siteForLogger);
                        }
                    }
                }

                catch (SPException spEx) { }
                finally
                {
                    // Enable Event Firing
                    EventFiringEnabled = true;
                }
        }

        /// <summary>
        /// An item is being deleted
        /// </summary>
        public override void ItemDeleting(SPItemEventProperties properties)
        {
            base.ItemDeleting(properties);
            replicatorOperation(properties, "Deleted");
        }
    }
}

//public static void UploadSPFile(string sourceFile, string destSPUrl, string destSPFolder)
//{
//    String fileToUpload = sourceFile;

//    String sharePointSite = destSPUrl;

//    String documentLibraryName = destSPFolder;

//    string fileurl = destSPUrl + destSPFolder;

//    string filename = "???";

//    string spFilename = fileurl + "/" + filename;

//    using (SPSite oSite = new SPSite(sharePointSite))
//    {
//        try
//        {
//            using (SPWeb oWeb = oSite.OpenWeb())
//            {
//                if (!System.IO.File.Exists(fileToUpload))

//                    throw new FileNotFoundException("File to upload was not found.", fileToUpload);

//                SPFolder SPLibrary = oWeb.Folders[fileurl]; // Prepare to upload

//                Boolean replaceExistingFiles = true;

//                String fileName = System.IO.Path.GetFileName(fileToUpload);

//                FileStream fileStream = File.OpenRead(fileToUpload);

//                SPFile spfilecheckout = oWeb.GetFile(spFilename);

//                if (spfilecheckout.Exists == true)
//                {
//                    spfilecheckout.CheckOut();

//                    //Checkout file
//                    SPLibrary.Update();

//                    //Update the library
//                }

//                SPFile spfile = SPLibrary.Files.Add(fileName, fileStream, replaceExistingFiles); // Upload document
//                SPLibrary.Update();

//                //Update the library
//                spfile.CheckIn(

//                "New Cf Directory File"); // Checkin document
//                spfile.Approve(

//                "Approved by System"); // Approve Document
//                SPLibrary.Update();
//            }
//        }

//        catch (SPException SPex)
//        {
//            Console.Write(SPex);
//        }

//    }

//}